
package cn.jbolt.core.enjoy.directive;

import cn.jbolt.core.kit.JBoltUserKit;
import cn.jbolt.core.permission.JBoltUserAuthKit;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;

/**
 * 界面上的权限控制功能 用来控制界面上的菜单、按钮等等元素的显示 #role(1)或者#role(1,2,3) ... #end
 */
public class RoleDirective extends Directive {

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		Long adminuserId = JBoltUserKit.getUserId();
		if (adminuserId != null) {
			boolean success = JBoltUserAuthKit.hasRole(adminuserId, false, getRoleArray(scope));
			if (success) {
				stat.exec(env, scope, writer);
			}
		}
	}

	/**
	 * 从 #role 指令参数中获取角色数组
	 */
	private Long[] getRoleArray(Scope scope) {
		Object[] values = exprList.evalExprList(scope);
		Long[] ret = new Long[values.length];
		for (int i = 0; i < values.length; i++) {
			if (values[i] instanceof Long) {
				ret[i] = Long.valueOf(values[i].toString());
			} else {
				throw new IllegalArgumentException("角色只能为 long 类型");
			}
		}
		return ret;
	}

	@Override
	public boolean hasEnd() {
		return true;
	}
}
